# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.decorators.http import require_POST
from django.views.generic import TemplateView

from common.admin import db as user_db
from common.settlement import db as settlement_db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.tz import utc_to_local_str

_LOGGER = track_logging.getLogger(__name__)


@require_POST
@response_wrapper
@token_required
def settlementOrderCreate(req):
    param_dct = json.loads(req.body)
    if req.user:
        param_dct['operator'] = req.user.nickname
        param_dct['operator_id'] = req.user.id
    settlement_db.create_settlement_withdraw(param_dct)
    return {}


class SettlementOrderView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and not query_dct.get('mch_id', ''):
            query_dct['mch_id'] = cond
        _LOGGER.info('SettlementOrderView get settlement_orders: %s, ', query_dct)

        items, total_count = settlement_db.list_settlement_order(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        param_dct = json.loads(req.body)
        settlement_db.upsert_settlement_order(param_dct)
        return {}

    def put(self, req):
        return self.post(req)

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SettlementOrderView, self).dispatch(*args, **kwargs)


class SingleSettlementOrderView(TemplateView):
    def get(self, req, id):
        mch_user = settlement_db.get_settlement_order(id=int(id))
        data = mch_user.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, id):
        return self.put(req, id)

    def put(self, req, id):
        query_dct = json.loads(smart_unicode(req.body))
        settlement_db.upsert_settlement_order(query_dct, int(id))
        return {}

    def patch(self, req, id):
        query_dct = json.loads(smart_unicode(req.body))
        settlement_db.upsert_settlement_order(query_dct, int(id))
        return {}

    def delete(self, req, id):
        settlement_db.delete_settlement_order(int(id))
        _LOGGER.info('delete settlement_order: %s, user: %s', id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleSettlementOrderView, self).dispatch(*args, **kwargs)
